package ldh.maker.controller;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import ldh.maker.ServerMain;
import ldh.maker.model.ModuleType;

import java.net.URL;
import java.util.ResourceBundle;

public class MainLancherController implements Initializable {

    @FXML private ChoiceBox<ModuleType> moduleChoiceBox;
    @FXML private Label descLabel;

    public void selectAction(ActionEvent actionEvent) {
        ModuleType moduleType = moduleChoiceBox.getSelectionModel().getSelectedItem();
        if (moduleType == null) {
            return;
        }
        Platform.runLater(()->{
            try {
                ServerMain serverMain = (ServerMain) moduleType.getClazz().newInstance();
                ServerMain.startDb(moduleType.getDbName());
                Stage stage = new Stage();
                serverMain.start(stage);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        moduleChoiceBox.getItems().addAll(ModuleType.values());
        moduleChoiceBox.setConverter(new StringConverter<ModuleType>() {
            @Override
            public String toString(ModuleType object) {
                return object.getName();
            }

            @Override
            public ModuleType fromString(String name) {
                return ModuleType.valueOf(name);
            }
        });

        moduleChoiceBox.getSelectionModel().selectedItemProperty().addListener((b, o, n)->{
            changeModule(n);
        });
    }

    private void changeModule(ModuleType module) {
        descLabel.setText(module.getDesc());
    }
}
